package com.betterjr.common.web;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;

import com.betterjr.common.utils.Collections3;

public class ParameterRequestWrapper extends HttpServletRequestWrapper {
    private Map params = new HashMap<>();

    public ParameterRequestWrapper(HttpServletRequest anRequest, Map anMap) {
        super(anRequest);
        this.params = anMap;
    }

    @Override
    public Map getParameterMap() {
        return params;
    }

    @Override
    public Enumeration getParameterNames() {
        Vector l = new Vector(params.keySet());
        return l.elements();
    }

    @Override
    public String[] getParameterValues(String name) {
        Object v = params.get(name);
        if (v == null) {
            return null;
        } else if (v instanceof String[]) {
            return (String[]) v;
        } else if (v instanceof String) {
            return new String[] { (String) v };
        } else {
            return new String[] { v.toString() };
        }
    }

    @Override
    public String getParameter(String name) {
        Object v = params.get(name);
        if (v == null) {
            return null;
        } else if (v instanceof String[]) {
            String[] strArr = (String[]) v;
            if (strArr.length > 0) {
                return strArr[0];
            } else {
                return null;
            }
        } else if (v instanceof String) {
            return (String) v;
        } else {
            return v.toString();
        }
    }

    public void addAllParameters(Map<String, Object> otherParams) {// 增加多个参数
        for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    public void addParameter(String name, Object value) {// 增加参数
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, value);
            } else if (value instanceof String) {
                params.put(name, new String[] { (String) value });
            } else {
                params.put(name, new String[] { String.valueOf(value) });
            }
        }
    }

    /**
     * 
     * @Title: removeParameter 
     * @Description: 移除某个paramters中的属性
     * @param rulelistRoleConstant TODO(说明)
     * @throws 
     * @author xuyp
     * @date 2017年11月25日 下午2:59:11
     */
    public void removeParameter(String rulelistRoleConstant) {

        if (StringUtils.isNoneBlank(rulelistRoleConstant)) {
            if (!Collections3.isEmpty(params)) {
                params.remove(rulelistRoleConstant);
            }
        }

    }
}
